package cn.jdemo.juc.locksupport;

import java.util.concurrent.locks.LockSupport;

/**
 * park阻塞一个线程，unpark唤醒一个线程
 *
 * unpark方法本质是生产许可
 * park方法本质是消费许可
 *
 * unpark方法可以在park方法前调用
 */
public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
        test1();
        // test2();
    }

    /**
     * 场景1: 先unpark然后park
     * 执行结果:
     * enter thread...
     * thread01 thread 执行 unpark
     * thread01 thread 执行 park
     * 后续业务~
     */
    public static void test1(){
        Thread thread01 = new Thread(() -> {
            try {
                Thread.sleep(0);
                System.out.println("enter thread...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("thread01 thread 执行 park");
            LockSupport.park();
            System.out.println("后续业务~");
        });
        thread01.start();
        LockSupport.unpark(thread01);
        System.out.println("thread01 thread 执行 unpark");
    }

    /**
     * 场景2: 先park然后unpark
     * 执行结果:
     * enter thread...
     * thread01 thread 执行 park
     * before后续业务前
     * thread01 thread 执行 unpark
     * 后续业务~
     */
    public static void test2() throws InterruptedException {
        Thread thread01 = new Thread(() -> {
            try {
                System.out.println("enter thread...");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("thread01 thread 执行 park");
            LockSupport.park();
            System.out.println("后续业务~");
        });
        thread01.start();
        Thread.sleep(2000);
        System.out.println("before后续业务前");
        LockSupport.unpark(thread01);
        System.out.println("thread01 thread 执行 unpark");
    }
}
